package com.wu.company.controller;

import com.wu.company.domain.LoginUser;
import com.wu.company.domain.SysRole;
import com.wu.company.domain.SysUser;
import com.wu.company.security.Md5;
import com.wu.company.service.SysUserRepository;
import com.wu.company.util.SpringSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class JspController {

    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private Md5 md5;

    @GetMapping("/login")
    public String login(HttpServletRequest request){
        request.getSession().removeAttribute("msg");
        return "login/login";
    }

    @GetMapping("/index")
    public String toIndex(Model model){
        String username = SpringSecurityUtils.getCurrentUserName();
        SysUser user = SpringSecurityUtils.getCurrentUser();
        String userIP = SpringSecurityUtils.getCurrentUserIp();
        model.addAttribute("id",user.getId());
        model.addAttribute("username",username);
        model.addAttribute("userIP",userIP);
        return "index";
    }

    @GetMapping("/editUser.action")
    public String editUser(Model model){
       SysUser user = SpringSecurityUtils.getCurrentUser();
        model.addAttribute("user",user);
        return "index";
    }

    @PostMapping("/updateUser.action")
    public String updateUser(Model model,SysUser user){
        SysUser sysUser = SpringSecurityUtils.getCurrentUser();
        user.setPassword(md5.encodePassword(user.getPassword(),null));
        user.setRoles(sysUser.getRoles());
        sysUserRepository.save(user);
        return "redirect:/editUser.action";
    }
}
